# coding:utf8
__author__ = 'golker'

from .appcreators import celeryapp
from .extensions import mymail
from flask_mail import Message
from flask import current_app
from .helpers import blog_render
from .models import Settings

celery = celeryapp()


@celery.task()
def celery_send_mail(msg):
    app = current_app._get_current_object()
    server = str(Settings.query.filter_by(type='MAIL_SERVER').first().value)
    port = int(Settings.query.filter_by(type='MAIL_PORT').first().value)
    tls = eval(Settings.query.filter_by(type='MAIL_USE_TLS').first().value)
    ssl = eval(Settings.query.filter_by(type='MAIL_USE_SSL').first().value)
    username = str(Settings.query.filter_by(type='MAIL_USERNAME').first().value)
    password = str(Settings.query.filter_by(type='MAIL_PASSWORD').first().value)
    admin = str(Settings.query.filter_by(type='ADMIN').first().value)
    app.config.update(MAIL_SERVER=server,
                      MAIL_PORT=port,
                      MAIL_USE_TLS=tls,
                      MAIL_USE_SSL=ssl,
                      MAIL_USERNAME=username,
                      MAIL_PASSWORD=password,
                      ADMIN_EMAIL=admin)
    mymail.init_app(app)
    with app.app_context():
        mymail.send(msg)


def send_email(subject, sender, recipients, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.html = html_body
    celery_send_mail.delay(msg)


def send_email_attach(subject, sender, recipients, html_body, attachments):
    app = current_app._get_current_object()
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.html = html_body
    with app.open_resource(attachments) as fp:
        msg.attach(attachments, 'imgs/zip', fp.read())
    celery_send_mail.delay(msg)


def register_mail(user):
    MAIL_USERNAME = Settings.query.filter_by(type='MAIL_USERNAME').first().value
    send_email(u"恭喜! %s 成功注册我的博客。" % user.email,
               MAIL_USERNAME,
               [user.email],
               blog_render("user/register_email.html",
                           user=user))


def backup_mail(attachments, msg):
    MAIL_USERNAME = Settings.query.filter_by(type='MAIL_USERNAME').first().value
    ADMINS = Settings.query.filter_by(type='ADMIN').first().value
    send_email_attach(u"blog的备份",
                      MAIL_USERNAME,
                      [ADMINS],
                      msg,
                      attachments=attachments)
